package com.cyzy;

import org.glassfish.tyrus.client.ClientManager;

import javax.websocket.*;
import java.net.URI;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@ClientEndpoint
public class DanmakuWsClient {

    private static final CountDownLatch latch = new CountDownLatch(1);
    private static Session session;

    // 连接成功回调
    @OnOpen
    public void onOpen(Session session) {
        DanmakuWsClient.session = session;
        System.out.println("✅ 客户端：WebSocket连接成功！Session ID: " + session.getId());
        try {
            // 发送测试消息
            session.getBasicRemote().sendText("自测用户:什么是Spring Boot？");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 接收后端消息回调
    @OnMessage
    public void onMessage(String message) {
        System.out.println("📥 客户端：收到后端广播消息: " + message);
    }

    // 连接错误回调
    @OnError
    public void onError(Throwable error) {
        System.err.println("❌ 客户端：WebSocket连接错误: " + error.getMessage());
        error.printStackTrace();
        latch.countDown(); // 发生错误时释放锁
    }

    // 连接关闭回调
    @OnClose
    public void onClose(Session session, CloseReason reason) {
        System.out.println("🔌 客户端：WebSocket连接关闭，原因: " + reason.getReasonPhrase());
        latch.countDown(); // 连接关闭时释放锁
    }

    public static void main(String[] args) {
        int maxRetries = 5;
        int retryCount = 0;

        while (retryCount < maxRetries) {
            try {
                retryCount++;
                System.out.println("尝试第 " + retryCount + " 次连接...");

                // 创建客户端管理器
                ClientManager client = ClientManager.createClient();

                // 设置连接超时（毫秒）
                client.getProperties().put(ClientManager.HANDSHAKE_TIMEOUT, 10000);

                // 连接后端WebSocket服务
                URI uri = new URI("ws://localhost:8081/danmaku-ws");
                System.out.println("正在连接到WebSocket服务: " + uri.toString());

                // 发起连接
                session = client.connectToServer(DanmakuWsClient.class, uri);
                System.out.println("✅ WebSocket连接已建立: " + session.getId());

                // 发送测试消息
                session.getAsyncRemote().sendText("测试用户:Hello WebSocket!");

                // 等待连接关闭或超时
                System.out.println("等待接收消息（30秒后自动关闭）...");
                if (!latch.await(30, TimeUnit.SECONDS)) {
                    System.out.println("等待超时，关闭连接");
                    if (session != null && session.isOpen()) {
                        session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "测试结束"));
                    }
                }

                break; // 连接成功，退出重试循环

            } catch (Exception e) {
                System.err.println("❌ 第 " + retryCount + " 次连接失败: " + e.getMessage());

                if (e.getCause() != null) {
                    System.err.println("失败原因: " + e.getCause().getMessage());
                }

                if (retryCount >= maxRetries) {
                    System.err.println("已达到最大重试次数，停止连接尝试");
                    break;
                }

                // 指数退避策略
                long delay = (long) Math.pow(2, retryCount) * 1000;
                System.out.println("等待 " + (delay/1000) + " 秒后重试...");
                try {
                    Thread.sleep(delay);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        }
    }
}